package com.xiaomi.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //通过请求参数拿到方法名,反射调用每一个方法,让子类继承,
        //提高代码复用性,也可以根据子类方法的返回值做跳转处理等
        String methodName = req.getParameter("method");
        if (methodName == null || "".equals(methodName)) {
            //非空判断,如果路径为null或者没有给method请求参数赋值,
            //统一重定向到首页来处理
            resp.sendRedirect("index.jsp");
        } else {
            //"redirect:/index.jsp";
            //根据子类方法的返回值判断以什么开头就截取返回值中的文件路径,进行重定向或者转发逻辑
            try {
                Class<? extends BaseServlet> clazz = this.getClass();
                Method method = clazz.getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
                String result = (String) method.invoke(this, req, resp);
                if (result != null) {
                    if (result.startsWith("forward")) {
                        String path = result.split("/")[1];
                        req.getRequestDispatcher(path).forward(req, resp);
                    } else if (result.startsWith("redirect")) {
                        String path = result.split("/")[1];
                        resp.sendRedirect(path);
                    } else {
                        resp.getWriter().write(result);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }
}
